import { login, getCurrentUser } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  user: null,
  userType: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_USER_TYPE: (state, userType) => {
    state.userType = userType
  }
}

const actions = {
  // 用户登录
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_USER', data.user)
        commit('SET_USER_TYPE', data.userType)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getCurrentUser().then(response => {
        const { data } = response
        if (!data) {
          reject(new Error('验证失败，请重新登录'))
        }
        commit('SET_USER', data)
        commit('SET_USER_TYPE', data.userType)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户登出
  logout ({ commit, state }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_USER', null)
      commit('SET_USER_TYPE', null)
      removeToken()
      resolve()
    })
  }
}

const getters = {
  token: state => state.token,
  user: state => state.user,
  userType: state => state.userType,
  isAdmin: state => state.userType === 3,
  isService: state => state.userType >= 2
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
